#include <string>
#include <windows.h>
#include <iostream>
using namespace std;

#include "registrymod.h"

#define WIN_32_LEAN_AND_MEAN
#define OVER_NINE_THOUSAND 9001

RegistryMod::RegistryMod()
{

}

RegistryMod::~RegistryMod()
{

}

void RegistryMod::writeToRegistry(string player, int hiscore)
{
	DWORD lRv;
	HKEY hKey;
	LPCTSTR player_reg = TEXT(player.c_str());
	DWORD dwDisposition;

	// Create a key if it did not exist
	lRv = RegCreateKeyEx(
		HKEY_CURRENT_USER,
		"Software\\MathNet\\Mathinator", //"Use Multi-Byte Character Set" by using L
		0,
		NULL,
		REG_OPTION_NON_VOLATILE,
		KEY_ALL_ACCESS,
		NULL,
		&hKey,
		&dwDisposition
		);

	RegSetValueEx(
		hKey,
		"Player",
		0,
		REG_SZ,
		(LPBYTE)player_reg,
		strlen(player_reg)+1
		);

	RegSetValueEx(
		hKey,
		"HiScore",
		0,
		REG_DWORD,
		reinterpret_cast<BYTE *>(&hiscore),
		sizeof(hiscore)
		);

	RegCloseKey(hKey);
}

void RegistryMod::readValueFromRegistry(void)
{
	HKEY hKey;

	//Check if the registry exists
	DWORD lRv = RegOpenKeyEx(
		HKEY_CURRENT_USER,
		"Software\\MathNet\\Mathinator",
		0,
		KEY_READ,
		&hKey
		);

	if (lRv == ERROR_SUCCESS)
	{
		DWORD BufferSize = sizeof(DWORD);
		DWORD dwRet;
		DWORD cbData;
		DWORD cbValNum = 0;
		DWORD dwType = REG_SZ;
		char cbValStr[OVER_NINE_THOUSAND];

		dwRet = RegQueryValueEx(
			hKey,
			"Player",
			NULL,
			&dwType,
			reinterpret_cast<LPBYTE>(cbValStr),
			&cbData
			);
		
		if( dwRet == ERROR_SUCCESS )
		{
			player = cbValStr;
		}
		//else cout<<"RegQueryValueEx failed " << dwRet << endl;
		

		dwRet = RegQueryValueEx(
			hKey,
			"HiScore",
			NULL,
			NULL,
			(LPBYTE)&cbValNum,
			&cbData
			);
		if( dwRet == ERROR_SUCCESS )
		{
			hiscore = cbValNum;
		}
		//else cout<<"RegQueryValueEx failed " << dwRet << endl;
		
	}
	/*else
	{
		cout<<"RegOpenKeyEx failed " << lRv << endl;
	}*/
}

string RegistryMod::getPlayerName(void)
{
	return player;
}

int RegistryMod::getHiscore(void)
{
	return hiscore;
}